<script setup lang='ts'>
import type { IAgreementPageList } from '@fl/api/anjutong/model/agreement-model'
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { agreementPageList, deletedAgreement, dictList } from '@fl/api/anjutong'
import { useRouter } from 'vue-router'

const router = useRouter()
type RowVO = {
    agreementContent: string
    agreementName: string
    agreementTypeName: string
    createTime: string
}

const xGrid = ref<VxeGridInstance<RowVO>>()

const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'agreementTypeName', title: '协议类型' },
        { field: 'sourceNameList', title: '协议来源' },
        { field: 'agreementUrl', title: '协议地址' },
        { field: 'agreementContent', slots: { default: 'agreementContent' }, title: '协议内容' },
        { field: 'agreementName', title: '协议文档' },
        { field: 'createTime', title: '上传时间' },
        { slots: { default: 'operation' }, title: '操作', width: 150 },

    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    pagerConfig: {
        currentPage: 1,
        enabled: true,
        pageSize: 10,
        pageSizes: [1, 20, 50, 100, 200, 500],
        total: 0,
    },
    showOverflow: true,
})

const options = ref<any[]>([])
const formInline = ref({
    date: '',
    type: '',
})
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
async function findList() {
    gridOptions.loading = true
    try {
        const options: IAgreementPageList = {
            endTime: formInline.value.date?.[1],
            pageNum: tablePage.currentPage,
            pageSize: tablePage.pageSize,
            startTime: formInline.value.date?.[0],
            type: formInline.value.type,
        }
        const data = await agreementPageList(options)
        console.log('🚀 ~ findList ~ data:', data)
        gridOptions.loading = false
        tablePage.total = data?.total
        gridOptions.data = data?.data
    }
    catch (error) {

    }
}
findList()

async function deleteData() {
    const $table = xGrid.value
    if ($table) {
        const selectRecords: any[] = $table.getCheckboxRecords()
        if (selectRecords.length) {
            const ids = selectRecords.map((item: any) => item.id)
            await deletedAgreement({ ids })
            ElMessage.success('删除成功')
            findList()
        }

        else { ElMessage.warning('请至少选择一项数据') }
    }
}
async function getDictData() {
    try {
        const data = await dictList({ dictType: 'agreement_type' })
        console.log('🚀 ~ getDictData ~ data:', data)
        options.value = data ?? []
    }
    catch (error) {
        options.value = []
    }
}
function preview(row: any) {
    if (row?.agreementUrl)
        return window.open(row?.agreementUrl, '_blank')
    try {
        const result = JSON.parse(row?.fileUrl)
        if (result?.fileUrl)
            window.open(result?.fileUrl, '_blank')
        else
            ElMessage.error('暂无数据')
    }
    catch (error) {
        ElMessage.error('暂无数据')
    }
}
getDictData()
function addData() {
    router.push('/content-center/protocol/form')
}
function reset() {
    formInline.value = {
        date: '',
        type: '',
    }
    findList()
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
function search() {
    tablePage.currentPage = 1
    findList()
}
</script>

<template>
    <div class="mb-20 bg-white p-30">
        <el-form :model="formInline">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="协议类型">
                        <el-select v-model="formInline.type"
                                   placeholder="请选择协议类型"
                                   style="width: 200px"
                                   clearable
                        >
                            <el-option v-for="item in options"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="6">
                    <el-form-item label="上传时间">
                        <el-date-picker v-model="formInline.date"
                                        type="daterange"
                                        range-separator="-"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        format="YYYY-MM-DD"
                                        clearable
                                        value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <div class="flex justify-end">
                        <ElButton type="primary"
                                  @click="search"
                        >
                            搜索
                        </ElButton>

                        <ElButton @click="reset">
                            重置
                        </ElButton>
                    </div>
                </el-col>
            </el-row>
        </el-form>
    </div>

    <div class="bg-white p-30">
        <div class="mb-20">
            <ElButton type="primary"
                      @click="addData"
            >
                新增
            </ElButton>

            <ElButton style="border:1px solid var(--el-color-primary)"
                      @click="deleteData"
            >
                删除
            </ElButton>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #agreementContent="{ row }">
                <div v-html="row.agreementContent" />
                <!-- 123 -->
            </template>

            <template #operation="{ row }">
                <span class="cursor-pointer text-#F53639"
                      @click="preview(row)"
                >预览</span>
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>
</template>
